package com.tkjt.pms.modules.report.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tkjt.pms.common.entity.TkIndexReport;
import com.tkjt.pms.common.utils.EsDateUtils;
import com.tkjt.pms.common.utils.OrgGroupUtil;
import com.tkjt.pms.modules.common.mapper.PMSCommonMapper;
import com.tkjt.pms.modules.common.mapper.TkIndexReportCtrlMapper;
import com.tkjt.pms.modules.common.mapper.TkIndexReportMapper;
import com.tkjt.pms.modules.common.service.TkDataConfigService;
import com.tkjt.pms.modules.common.service.TkIndexReportService;
import com.tkjt.pms.modules.report.mapper.ReportDownLoadMapper;
import com.tkjt.pms.modules.report.service.ReportExcelService;
import com.tkjt.pms.modules.report.vo.DatagridVO;
import com.tkjt.pms.modules.report.vo.HeadConditionVO;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.def.MapExcelConstants;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.tkjt.pms.modules.report.service.ReportCreator;
import com.tkjt.pms.server.IndexServer;
import com.tkjt.pms.server.common.ServerParam;
import com.tkjt.pms.server.common.ServerTask;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ReportCreatorImpl implements ReportCreator {

	@Autowired
	private IndexServer indexServer;

	@Autowired
	PMSCommonMapper commonMapper;

	@Autowired
	TkIndexReportMapper tkIndexReportMapper;

	@Autowired
	ReportExcelService reportExcelService;

	@Autowired
	private TkIndexReportService tkIndexReportService;

	@Autowired
	private ReportDownLoadMapper reportDownLoadMapper;
	
	@Value(value = "${pms.report.path}")
	private String reportPath;

	@Autowired
	private TkDataConfigService tkDataConfigService;

	@Autowired
	TkIndexReportCtrlMapper tkIndexReportCtrlMapper;

	@Override
	public void doCreator(String indexYearMonth, Set<String> reportCodes,LoginUser loginUser) {
		log.info("start report creator...");
		
		List<ServerTask> serverTasks = new ArrayList<ServerTask>();
		for(String reportCode : reportCodes) {
			ServerParam params = new ServerParam();
			params.setServerServiceName(ReportCreator.SERVICE_REPORT_CREATOR);
			params.addParam("indexYearMonth", indexYearMonth);
			params.addParam("reportCode", reportCode);
			params.addParam("reportPath", reportPath);
			params.addParam("loginUser",loginUser);
			ServerTask oneTask = new ServerTask(params);
			serverTasks.add(oneTask);
			if(reportCode.contains("@")){
				String fainalReportCode = "isTotal@"+reportCode;
				params = new ServerParam();
				params.setServerServiceName(ReportCreator.SERVICE_REPORT_CREATOR);
				params.addParam("indexYearMonth", indexYearMonth);
				params.addParam("reportCode", fainalReportCode);
				params.addParam("reportPath", reportPath);
				params.addParam("loginUser",loginUser);
				oneTask = new ServerTask(params);
				serverTasks.add(oneTask);
			}
		}
		indexServer.doIndexServer(serverTasks);
	}

	@Override
	public Result<?> detailConditions(LoginUser loginUser,DatagridVO datagridVO) {
		String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
		String indexYearMonth = datagridVO.getIndexYearMonth();
		if(StringUtils.isEmpty(indexYearMonth)){
			indexYearMonth = EsDateUtils.getIndexYearMonth(new Date());
		}
		List<Map<String,Object>> indexPeriods = commonMapper.getDictItemByDictCode("yearMonth");
		HeadConditionVO headConditionVO = new HeadConditionVO();
		headConditionVO.setIndexPeriods(indexPeriods);
		String[] reportCodes = {"RDPH","RHCH","RDP","RDP"};
		List<Map<String,Object>> indexGroups = new ArrayList<>();
		for (String reportCode : reportCodes){
			QueryWrapper<TkIndexReport> reportQuery = new QueryWrapper<>();
			reportQuery.lambda().eq(TkIndexReport::getIndexYearMonth,indexYearMonth);
			reportQuery.lambda().eq(TkIndexReport::getReportCode,reportCode);
			TkIndexReport tkIndexReport = tkIndexReportService.getOne(reportQuery);
			datagridVO.setIndexGroup(tkIndexReport.getIndexGroup().equals("1")?"G":"C");
			Map<String,String> detailConditions = new HashMap<>();
			detailConditions.put("conditions","conditions");
			Map<String, Object> stringObjectMap = reportExcelService.buildReportExcelData(false,indexYearMonth, reportCode, loginUser, detailConditions,datagridVO,dataType);
			@SuppressWarnings("unchecked")
			List<ExcelExportEntity> list = (List<ExcelExportEntity>) stringObjectMap.get(MapExcelConstants.ENTITY_LIST);
			List<Map<String,Object>> tabHeader = new ArrayList<>();
			for (ExcelExportEntity excelExportEntity : list){
				String key = excelExportEntity.getKey().toString();
				String name = excelExportEntity.getName();
				if(excelExportEntity.getList() != null && excelExportEntity.getList().size() > 0){
					for(ExcelExportEntity childExcelExportEntity : excelExportEntity.getList()){
						Map<String,Object> map = new HashMap<>();
						if(name.contains("(")){
							name = name.replace("(","-");
							name = name.replace(")","");
						}
						map.put("name",name+"("+childExcelExportEntity.getName()+")");
						map.put("code",key+childExcelExportEntity.getKey().toString());
						tabHeader.add(map);
					}

				}else{
					Map<String,Object> map = new HashMap<>();
					map.put("name",key);
					map.put("code",name);
					tabHeader.add(map);
				}

			}
			Map<String,Object> reportMap = new HashMap<>();
			reportMap.put("name",tkIndexReport.getReportName());
			reportMap.put("code",reportCode);
			reportMap.put("tabHeader",tabHeader);
			indexGroups.add(reportMap);
		}
		headConditionVO.setIndexReport(indexGroups);
		return Result.ok(headConditionVO);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Result<?> detailDatagrid(LoginUser loginUser,DatagridVO datagridVO) {
		String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
		String indexYearMonth = datagridVO.getIndexYearMonth();
		if(StringUtils.isEmpty(indexYearMonth)){
			indexYearMonth = EsDateUtils.getIndexYearMonth(new Date());
		}
		String reportCode = datagridVO.getIndexReport();
		if(StringUtils.isEmpty(reportCode)){
			return Result.error("参数缺失");
		}
		Integer pageNo = datagridVO.getPageNo();
		if(pageNo == null){
			return Result.error("参数缺失");
		}
		Integer pageSize = datagridVO.getPageSize();
		if(pageSize == null){
			return Result.error("参数缺失");
		}
		//Map<String,Object> param = new HashMap<>();
		datagridVO.setMin((pageNo - 1) * pageSize);
		datagridVO.setMax(pageSize);
		QueryWrapper<TkIndexReport> reportQuery = new QueryWrapper<>();
		reportQuery.lambda().eq(TkIndexReport::getIndexYearMonth,indexYearMonth);
		reportQuery.lambda().eq(TkIndexReport::getReportCode,reportCode);
		TkIndexReport tkIndexReport = tkIndexReportService.getOne(reportQuery);
		String orgGroup = OrgGroupUtil.changeToCG(tkIndexReport.getIndexGroup());
		datagridVO.setIndexGroup(orgGroup);
		Map<String,String> detailConditions = new HashMap<>();
		detailConditions.put("detail","detail");
		Map<String, Object> stringObjectMap = reportExcelService.buildReportExcelData(false,indexYearMonth, reportCode, loginUser, detailConditions,datagridVO,dataType);
		int count = reportDownLoadMapper.selectCount(datagridVO);
		List<Map<String, Object>> list = (List<Map<String, Object>>) stringObjectMap.get(MapExcelConstants.MAP_LIST);
		List<Map<String, Object>> resultList = new ArrayList<>();
		for (Map<String, Object> map : list){
			List<Map<String, Object>> indexValueList = new ArrayList<>();
			Map<String,Object> rowsPanMap = new HashMap<>();
			Set<String> keys = map.keySet();
			Iterator<String> iterator = keys.iterator();
			boolean isFirst = true;
			while(iterator.hasNext()){
				String key = iterator.next();

				if(map.get(key) instanceof ArrayList){
					List<Map<String,Object>> indexValues = (ArrayList<Map<String,Object>>)map.get(key);
					if(isFirst){
						for(int i = 0 ; i < indexValues.size() ; i++){
							Map<String,Object> dataMap = new HashMap<>();
							Set<String> childKyes = indexValues.get(i).keySet();
							Iterator<String> iteratorChild = childKyes.iterator();
							while(iteratorChild.hasNext()){
								String childKey = iteratorChild.next();
								dataMap.put(key+childKey,indexValues.get(i).get(childKey));
							}
							indexValueList.add(dataMap);
						}
						isFirst = false;
					}else{
						for(int i = 0 ; i < indexValues.size() ; i++){
							Set<String> childKyes = indexValues.get(i).keySet();
							Iterator<String> iteratorChild = childKyes.iterator();
							Map<String,Object> dataMap = indexValueList.get(i);
							while(iteratorChild.hasNext()){
								String childKey = iteratorChild.next();
								dataMap.put(key+childKey,indexValues.get(i).get(childKey));
							}
							indexValueList.set(i,dataMap);
						}
					}
				}else{
					rowsPanMap.put(key,map.get(key));
				}
			}
			for(int i = 0 ; i < indexValueList.size() ; i++){
				Map<String,Object> finalMap = indexValueList.get(i);
				finalMap.putAll(rowsPanMap);
				indexValueList.set(i,finalMap);
			}
			resultList.addAll(indexValueList);
		}

		Page<Map<String,Object>> finalPage = new Page<Map<String,Object>>(pageNo, pageSize);
		finalPage.setTotal(count);
		finalPage.setCurrent(pageNo);
		finalPage.setSize(pageSize);
		int pages = count / pageSize;
		if (count % pageSize > 0) {
			pages += 1;
		}
		finalPage.setPages(pages);
		finalPage.setRecords(resultList);
		return Result.ok(finalPage);
	}


}
